package com.jiyinit.web.core.business.service;

import com.jiyinit.core.framework.base.paging.PagingResult;
import com.jiyinit.core.framework.base.util.Check;
import com.jiyinit.core.framework.base.util.MD5Util;
import com.jiyinit.core.framework.dao.mybatis.paginator.domain.PageBounds;
import com.jiyinit.web.core.business.dao.TabCoreUserDao;
import com.jiyinit.web.core.business.dao.TabCoreUserRoleDao;
import com.jiyinit.web.core.business.dto.UserRequest;
import com.jiyinit.web.core.business.entity.TabCoreOrgEntity;
import com.jiyinit.web.core.business.entity.TabCoreUserEntity;
import com.jiyinit.web.core.business.entity.TabCoreUserRoleEntity;
import com.jiyinit.web.core.business.vo.ContactsVo;
import com.jiyinit.web.core.business.vo.OrgTreeVo;
import com.jiyinit.web.core.business.vo.UserInfoVo;
import com.jiyinit.web.core.common.util.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

/**
 * <p></p>
 * <p>
 * <PRE>
 * <BR>	修改记录
 * <BR>-----------------------------------------------
 * <BR>	修改日期			修改人			修改内容
 * </PRE>
 *
 * @author zhaolaiwei
 * @version 1.0
 * @date 2017/4/11 17:59
 * @since 1.0
 */
@Service("core.userServiceImpl")
public class UserServiceImpl {

    @Resource(name = "core.tabCoreUserDao")
    private TabCoreUserDao tabCoreUserDao;

    @Resource(name = "core.tabCoreUserRoleDao")
    private TabCoreUserRoleDao tabCoreUserRoleDao;

    @Resource(name = "core.orgServiceImpl")
    private OrgServiceImpl orgService;

    public List<ContactsVo> findFriends(Integer userId,String userName){
        return tabCoreUserDao.findFriendsByCon(userId,userName);
    }

    public int updatePinyin(List<TabCoreUserEntity> list){
        return tabCoreUserDao.updatePinyin(list);
    }

    public PagingResult<TabCoreUserEntity> findUsers(PageBounds pageBounds){
        return tabCoreUserDao.findUsers(pageBounds);
    }

    public List<TabCoreUserEntity> findUserByOrgId(Integer orgId){
        return tabCoreUserDao.findUserByOrgId(orgId);
    }

    public int selectMaxOrder(Integer orgId){
        return tabCoreUserDao.selectMaxOrder(orgId);
    }

    public int insert(TabCoreUserEntity tabCoreUser,Integer roleId) {
        int num = tabCoreUserDao.insert(tabCoreUser);
        if(!Check.isNullObj(roleId)) {
            TabCoreUserRoleEntity userRole = getInsertRoleUserByRoleId(tabCoreUser.getUserId(), roleId);
            tabCoreUserRoleDao.insert(userRole);
        }
        return num;
    }

    /**
     * 用户登录
     * @author zhaolaiwei
     * @create 2017/4/11 18:01
     * @param
     * @return
     */
    public TabCoreUserEntity login(String loginName,String password){
        TabCoreUserEntity tabCoreUser = tabCoreUserDao.getUserInfoByLoginName(loginName);
        if(!Check.isNullObj(tabCoreUser)){
            String md5password = MD5Util.MD5Encode(password);
            if(md5password.equalsIgnoreCase(tabCoreUser.getPassword()) && new Integer(1).equals(tabCoreUser.getUserStatus())){
                return tabCoreUser;
            }
        }
        return null;
    }

    /**
     * 分页查询用户信息
     * @author zhaolaiwei
     * @create 2017/4/13 9:00
     * @param userRequest
     * @return
     */
    public PagingResult<UserInfoVo> getUserInfoListByCondiction(UserRequest userRequest){
        return tabCoreUserDao.getUserInfoListByCondiction(userRequest);
    }

    /**
     * 
         * 按机构查询用户
         * @author wuyuefeng
         * @create 2017年4月27日 下午2:22:51
         * @param 
         * @return
     */
    public PagingResult<UserInfoVo> findUsersByOrId(UserRequest userRequest){
        return tabCoreUserDao.getUserInfoListByCondiction(userRequest);
    }
    
    
    /**
     * 通过用户ID查询用户信息
     * @param userId
     * @return
     */
    public TabCoreUserEntity getUserInfoByUserId(Integer userId){
        return tabCoreUserDao.getUserInfoById(userId);
    }

    /**
     * 修改用户信息
     * @param tabCoreUser
     * @return
     */
    public int updateUserInfoById(TabCoreUserEntity tabCoreUser,Integer roleId) {
        int num = tabCoreUserDao.updateUserInfoById(tabCoreUser);
        TabCoreUserRoleEntity userRole = tabCoreUserRoleDao.selectByUserId(tabCoreUser.getUserId());
        //如果改变则更新
        if(!Check.isNullObj(roleId) && !userRole.getRoleId().equals(roleId)){
            userRole = getModifyRoleUserByRoleId(tabCoreUser.getUserId(),roleId);
            tabCoreUserRoleDao.updateByUserId(userRole);
        }
        return num;
    }

    /**
     * 删除用户信息
     * @param userIds
     * @return
     */
    public int deleteUserLogicByIds(Integer[] userIds){
        return tabCoreUserDao.deleteUserLogicByIds(userIds);
    }

    /**
     * 通过登录名查询用户信息
     * @param loginName
     * @return
     */
    public TabCoreUserEntity getUserInfoByLoginName(String loginName){
        return tabCoreUserDao.getUserInfoByLoginName(loginName);
    }

    private TabCoreUserRoleEntity getInsertRoleUserByRoleId(Integer userId,Integer roleId){
        TabCoreUserRoleEntity userRole = new TabCoreUserRoleEntity();
        userRole.setRoleId(roleId);
        userRole.setUserId(userId);
        userRole.setIsDelete(0);
        userRole.setCreateId(UserUtil.getCurrentUser().getUserId());
        userRole.setCreateTime(new Date());
        userRole.setLastModifyId(UserUtil.getCurrentUser().getUserId());
        userRole.setLastModifyTime(new Date());
        return userRole;
    }

    private TabCoreUserRoleEntity getModifyRoleUserByRoleId(Integer userId,Integer roleId){
        TabCoreUserRoleEntity userRole = new TabCoreUserRoleEntity();
        userRole.setRoleId(roleId);
        userRole.setUserId(userId);
        userRole.setLastModifyId(UserUtil.getCurrentUser().getUserId());
        userRole.setLastModifyTime(new Date());
        return userRole;
    }

    public List<ContactsVo> findUsersByCon(List<TabCoreOrgEntity> orgList,String userName){
        return tabCoreUserDao.findUsersByCon(orgList, userName);
    }

    public List<ContactsVo> getUsers( List<TabCoreOrgEntity> orgList){
        return tabCoreUserDao.getUsers(orgList);
    }

    public OrgTreeVo findContacts(UserRequest request){
        //根据当前登录者的orgId，查询出最高的orgId
        Integer parentId = orgService.getTopParentOrgId(request.getOrgId());
        //根据查询出的所有的子机构
        List<TabCoreOrgEntity> orgList = orgService.getChildOrgById(parentId);

        List<ContactsVo> users =  this.getUsers(orgList);
        //生成机构树
        OrgTreeVo node = new OrgTreeVo();
        for(TabCoreOrgEntity org : orgList){
            if(org.getOrgId().intValue() == parentId){
                node.setOrgId(org.getOrgId());
                node.setOrgName(org.getOrgName());
                node.setOrgLevel(org.getOrgLevel());
                node.setChilds(getchilds(org.getOrgId(),orgList));
            }
        }

        addUsers(node,users);
        return node;
    }

    public List<ContactsVo> findContactsAndroid(UserRequest request) {
        //根据当前登录者的orgId，查询出最高的orgId
        Integer parentId = orgService.getTopParentOrgId(request.getOrgId());
        //根据查询出的所有的子机构
        List<TabCoreOrgEntity> orgList = orgService.getChildOrgById(parentId);
        List<ContactsVo> users =  this.getUsers(orgList);
        return users;
    }

    public void addUsers(OrgTreeVo node, List<ContactsVo> users){
        //在机构树中增加用户
        List<ContactsVo> orgUser = new ArrayList<>();
        for(ContactsVo user :users){
            if(node.getOrgId().intValue() == user.getOrgId().intValue()){
                orgUser.add(user);
            }
            node.setUsers(orgUser);
            for(OrgTreeVo  child : node.getChilds()){
                addUsers(child,users);
            }
        }
    }

    public List<OrgTreeVo> getchilds(Integer orgId,List<TabCoreOrgEntity> orgList){
        List<OrgTreeVo> childOrgs = new ArrayList<>();

        for(TabCoreOrgEntity org : orgList){
            if(org.getParentId().intValue() == orgId){
                OrgTreeVo node = new OrgTreeVo();
                node.setOrgId(org.getOrgId());
                node.setOrgName(org.getOrgName());
                node.setOrgLevel(org.getOrgLevel());
                node.setChilds(getchilds(org.getOrgId(),orgList));
                childOrgs.add(node);
            }
        }
        return childOrgs;
    }

    public List<ContactsVo> queryUsers(String param){

        List<ContactsVo> list = tabCoreUserDao.queryUsers(param);
        return list;
    }

    public List<UserInfoVo> findUsersByfunRoleId(List<TabCoreOrgEntity> orgList,Integer funRoleId){
        return tabCoreUserDao.findUsersByfunRoleId(orgList,funRoleId);
    }

    public Integer findCount(){
        return tabCoreUserDao.findCount();
    }

    public List<ContactsVo> getPartTimeUserInfo(List<TabCoreOrgEntity> orgList){
        return tabCoreUserDao.getPartTimeUserInfo(orgList);
    }

     /**
      * 修改用户头像
      * @author liuzongguang
      * @create 2018/7/11 10:00
      * @param tabCoreUser
      * @return
      */
    public int updateUserAvatar(TabCoreUserEntity tabCoreUser) {
        int num = tabCoreUserDao.updateUserAvatar(tabCoreUser);
        return num;
    }

    public List<TabCoreUserEntity> findUsersList(){
        return tabCoreUserDao.findUsersList();
    }

    public int updateBySalary(TabCoreUserEntity tabCoreUser) {
        return tabCoreUserDao.updateBySalary(tabCoreUser);
    }

    public TabCoreUserEntity getUserInfoByUserCertificateNo(String userCertificateNo){
        return tabCoreUserDao.getUserInfoByUserCertificateNo(userCertificateNo);
    }

    /**
     *通过父id 获取机构id下的所有用户
     */
    public PagingResult<TabCoreUserEntity> findUserByparentId(UserRequest userRequest){
        return tabCoreUserDao.findUserByparentId(userRequest);
    }

    public PagingResult<UserInfoVo> getUserInfoListByUserName(UserRequest userRequest){
        return tabCoreUserDao.getUserInfoListByUserName(userRequest);
    }
}
